layui.define(['table', 'treeTable', 'form', 'laydate', 'tableSelect'], function (exports) {

    var $ = layui.$
        , form = layui.form
        , table = layui.table
        , setter = layui.setter
        , admin = layui.admin
        , treeTable = layui.treeTable
        , tableSelect = layui.tableSelect
        , layer = layui.layer
        , laydate = layui.laydate
        , admin = layui.admin


    var w = document.documentElement.clientWidth;


    var goodscode = $('#goodscode', parent.document).val();
    if (goodscode == '') {
        layer.msg('请输入商品编码后在进行查询');
        return false;
    }
    var homeSelect = $('#goodscode', parent.document).val();
    var colsArr;

    init();

    function init() {
        $("#systemname").html('已选择系统:全部')
        loadTableNull("0");
    }


    //日期
    laydate.render({
        elem: '#sdate'
        , type: 'datetime'
        , trigger: 'click'
    });
    laydate.render({
        elem: '#edate'
        , type: 'datetime'
        , trigger: 'click'
    });

    // hiddendiv();
    // function hiddendiv() {
    //     $("#table").show();
    //     $("#form").hide();
    //     loadTable("");
    // }
    //
    // function showdiv() {
    //     $("#table").hide();
    //     $("#form").show();
    // }


//	-------------------------------------------------------------------------------------------


    function loadTable(id) {

        colsArr = [
            {fixed: 'left', field: 'zizeng', title: '序号', align: 'center', templet: '#zizeng'},
            // {field: 'supplier', title: '供应商', width: 100, align: 'center', edit: 'text'},
            {field: 'supplier', title: '供应商',width:100,align:'center', event: 'goodsId', templet: '#goodsSelect'},
            {field: 'suppliername', title: '供应商名称', width: 120, align: 'center'},
            {field: 'inprice', title: '进价', width: 100, align: 'center', edit: 'text'},
            {field: 'intaxrate', title: '进项税率', width: 100, align: 'center', edit: 'text'},
            {field: 'boxnumber', title: '装箱数量', width: 100, align: 'center', edit: 'text'},
            {field: 'attribute', title: '属性', width: 220, align: 'center', templet: '#unitSelect'},
            {field: 'startdate', title: '入场时间', width: 160, align: 'center', event: 'startd'},
            {field: 'enddate', title: '退场时间', width: 160, align: 'center', event: 'endd'},
            {field: 'remark', title: '备注', width: 100, align: 'center', edit: 'text'},
            {fixed: 'right', title: '操作', width: 80, toolbar: '#opeTable'},

        ];
        var width = 950;
        if (w < 1500) {
            width = 850
        }


        //带查询条件
        var grouphaveCol = [];
        grouphaveCol.push({"colName": "goodscode", "colValue": goodscode});
        grouphaveCol.push({"colName": "flag", "colValue": 0});
        grouphaveCol.push({"colName": "id", "colValue": id});

        //供应商
        table.render({
            elem: '#LAY-genius-table'
            , url: setter.host + '/goods_system_supplier/getSelectBody'
            , cols: [colsArr]
            , method: 'post'
            , contentType: 'application/json; charset=utf-8'
            , where: {'haveCol': grouphaveCol}
            , page: true
            , limit: 20
            , limits: [30, 50, 70]
            // ,height: '500px'
            , width: width
            , done: function () {
                delete this.where;

            }
        });


    }

    function loadTableNull(id) {

        colsArr = [
            {fixed: 'left', field: 'zizeng', title: '序号', align: 'center', templet: '#zizeng'},
            {field: 'supplier', title: '供应商', width: 100, align: 'center'},
            {field: 'suppliername', title: '供应商名称', width: 120, align: 'center'},
            {field: 'inprice', title: '进价', width: 100, align: 'center'},
            {field: 'intaxrate', title: '进项税率', width: 100, align: 'center'},
            {field: 'boxnumber', title: '装箱数量', width: 100, align: 'center'},
            {
                field: 'attribute', title: '属性', width: 220, align: 'center', templet: function (d) {
                    var string = '';
                    if (d.attribute.charAt('0') == '1') {
                        string = string + '可订货'
                    } else {
                        string = string + '不可订货'
                    }
                    if (d.attribute.charAt('2') == '1') {
                        string = string + ',可退货'
                    } else {
                        string = string + ',不可退货'
                    }
                    return string;
                }
            },
            {field: 'startdate', title: '入场时间', width: 160, align: 'center'},
            {field: 'enddate', title: '退场时间', width: 160, align: 'center'},
            {field: 'remark', title: '备注', width: 100, align: 'center'},
            {fixed: 'right', title: '操作', width: 110, toolbar: '#opeTable'},
        ];
        var width = 950;
        if (w < 1500) {
            width = 850
        }
        //带查询条件
        var grouphaveCol = [];
        grouphaveCol.push({"colName": "goodscode", "colValue": goodscode});
        grouphaveCol.push({"colName": "flag", "colValue": 0});
        grouphaveCol.push({"colName": "id", "colValue": id});

        //供应商
        table.render({
            elem: '#LAY-genius-table'
            , url: setter.host + '/goods_system_supplier/getSelectBody'
            , cols: [colsArr]
            , method: 'post'
            , contentType: 'application/json; charset=utf-8'
            , where: {'haveCol': grouphaveCol}
            , page: true
            , limit: 20
            , limits: [30, 50, 70]
             ,height: '700px'
            , width: width
            , done: function () {
                delete this.where;

            }
        });


    }


//	-------------------------------------------------------------------------------------------
    var roleTable = treeTable.render({
        elem: '#LAY-role-list',
        tree: {
            iconIndex: 1,  // 折叠图标显示在第几列
//			idName: 'id',  // 自定义id字段的名称
            arrowType: 'arrow1' //箭头类型
        },
//		parent_key: 'fatherid',
        height: '600',
        cols: colsArr = [
            {field: 'id', title: 'id', hide: true},
            {field: 'name', title: '名称'}
        ],
        method: 'get',
        contentType: "application/json; charset=utf-8",
        url: setter.host + '/unite_platform/goods_system_supplier/roleList'

    });


    var objid;
    treeTable.on('row(LAY-role-list)', function (obj) {
        // objid=obj.data.id
        var delId = {};
        delId.id = obj.data.id;
        layui.admin.req({
            url: layui.setter.host + '/goods_system_supplier/roleList_dept'
            , type: 'post'
            , dataType: 'json'
            , contentType: "application/json; charset=utf-8"
            , data: JSON.stringify(delId)
            , done: function (res) {
                $("#systemname").html('已选择系统:' + obj.data.name)
                if (res.data.length == 0) {
                    objid = obj.data.id;
                    loadTable(obj.data.id);
                } else {
                    loadTableNull(obj.data.id);
                }
            }
        });


    });

    //监听锁定操作
    form.on('checkbox(lockDemo)', function (obj) {

        if (obj.elem.checked) {
            this.value = "1";
        } else {
            this.value = "0";
        }

    });


//	-------------------------------------------------------------------------------------------	
    table.on('tool(LAY-genius-table)', function (obj) {


        var data = obj.data;

        if (obj.event === 'del') {
            layer.confirm('确认删除行么', function (index) {

                data.flag = 1;
                layui.admin.req({
                    url: layui.setter.host + '/goods_system_supplier/edit'
                    , type: 'post'
                    , dataType: 'json'
                    , contentType: "application/json; charset=utf-8"
                    , data: JSON.stringify(data)
                    , done: function (res) {
                        //请求成功后
                        if (res.status == setter.response.statusCode.status_Success) {
                            layer.msg(res.msg);
                            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                        }
//									table.render();
                    }
                });

                layer.close(index);
            });
        } else if (obj.event === 'edit') {
            var modifyUrL = layui.setter.host + '/goods_system_supplier/edit';
            if (data.actionType == 'add') {
                modifyUrL = layui.setter.host + '/goods_system_supplier/add';
                data.system = objid;
            }
            data.goodscode = goodscode;

            var din = $(obj.tr).find('td:eq(6) input:eq(0)').attr('value');
            var tui = $(obj.tr).find('td:eq(6) input:eq(1)').attr('value');
            //复选框
            if (din == '1' && tui == '1') {
                data.attribute = '1,1';
            } else if (din == '0' && tui == '0') {
                data.attribute = '0,0';
            } else if (din == '1' && tui == '0') {
                data.attribute = '1,0';
            } else if (din == '0' && tui == '1') {
                data.attribute = '0,1';
            }

            data.startdate = $(obj.tr).find('td:eq(7)').children().html();
            data.enddate = $(obj.tr).find('td:eq(8)').children().html();


//			data.startdate=$(obj.tr).find('td:eq(7) input').val();
//			data.enddate=$(obj.tr).find('td:eq(8) input').val();

            layui.admin.req({
                url: modifyUrL
                , type: 'post'
                , dataType: 'json'
                , contentType: "application/json; charset=utf-8"
                , data: JSON.stringify(data)
                , done: function (res) {
//							console.log(res);
                    //请求成功后修改状态为编辑
                    if (res.status == setter.response.statusCode.status_Success) {
//								console.log(table);
                        //带查询条件
//							 	var grouphaveCol = [];
//							 	grouphaveCol.push({"colName":"goodscode","colValue":goodscode});
//							 	grouphaveCol.push({"colName":"flag","colValue":0});
//						 		grouphaveCol.push({"colName":"id","colValue":objid});
//								table.reload("LAY-genius-table",{url: setter.host + '/goods_system_supplier/getSelectBody',where:{'haveCol':grouphaveCol}});
                    }
                    layer.msg(res.msg);

                }
            });
        } else if (obj.event === 'startd') {//打开日期弹窗
            var field = $(this).data('field');
            laydate.render({

                elem: this.firstChild
                , trigger: 'click'
                , show: true //直接显示
                , type: 'datetime'
                , closeStop: this
                , done: function (value, date) {

                    data[field] = value;
//	            obj.update(data);
                }
            });


        } else if (obj.event === 'endd') {//打开日期弹窗
            var field = $(this).data('field');
            laydate.render({
                elem: this.firstChild
                , show: true //直接显示
                , trigger: 'click'
                , type: 'datetime'
                , closeStop: this
                , done: function (value, date) {
                    data[field] = value;
//	            obj.update(data);
                }
            });
        } else if (obj.event === 'goodsId') {//打开商品弹窗

            var inputId = $(obj.tr).find('td:eq(1) input').attr('id');
            var goodsColsArr = [
                {type: 'radio'},
                {field: 'suppliercode', title: '供应商编码', sort: false},
                {field: 'suppliername', title: '供应商名称', sort: false},
            ];
            var goodsTableHead = '';
            layui.each(goodsColsArr, function (inx, val) {
                goodsTableHead += val.hasOwnProperty('field') ? val.field + ',' : ',';
            })
            goodsTableHead = goodsTableHead.substring(goodsTableHead.indexOf(',') + 1, goodsTableHead.length - 1);
            //	                     	goodsbrandnameTableHead = goodsbrandnameTableHead.substring(0,goodsbrandnameTableHead.length-1);
            //带查询条件
            var haveCol = [];
//			haveCol.push({"colName":"flag","colValue":0});
            tableSelect.render({
                elem: '#' + inputId,
                checkedKey: 'suppliercode',
                height: '350',
                width: '450',
                searchType: 'more',
                searchList: [
                    {searchKey: 'suppliercode', searchPlaceholder: '供应商编码'},
                ],
                table: {
                    url: layui.setter.host + '/supplier_info/getSelectBody'
                    , method: 'post'
                    , where: {'headField': goodsTableHead, 'haveCol': haveCol}
                    , contentType: 'application/json; charset=utf-8'
                    , page: true
                    , groups: 2
                    , limit: 20
                    , limits: [20, 30, 50]
                    , text: {
                        none: '暂无相关数据'
                    }
                    , cols: [goodsColsArr]
                },
                done: function (elem, data) {

                    var goodsIdArray = [];
                    var goodsnameArray = [];
                    layui.each(data.data, function (index, item) {
                        goodsIdArray.push(item.suppliercode);
                        goodsnameArray.push(item.suppliername);
                    })
                    //刷新表格的值
                    obj.update({
                        supplier: goodsIdArray.join(",")
                        , suppliername: goodsnameArray.join(",")

                    });
                    $('#' + inputId).val(goodsIdArray.join(","));
                }
            });
        }
    });


//	-------------------------------------------------------------------------------------------	

    var active = {

        addTable: function () {
            var tableBak = [];
            var dataBak = table.cache['LAY-genius-table'];
            for (var i = 0; i < dataBak.length; i++) {
                tableBak.push(dataBak[i]);      //将之前的数组备份
            }
            var tableOne = {};
            tableOne.LAY_TABLE_INDEX = dataBak.length;
            tableOne.supplier = '';
            tableOne.suppliername = '';
            tableOne.inprice = '';
            tableOne.intaxrate = '';
            tableOne.boxnumber = "";
            tableOne.attribute = "";
            tableOne.startdate = "";
            tableOne.enddate = '';
            tableOne.remark = '';
            tableOne.flag = "0";
            //新增使用新增方法
            tableOne.actionType = "add";
            tableBak.push(tableOne);			//重新刷新表格
            table.reload("LAY-genius-table", {
                url: ""
                , data: tableBak   // 将新数据重新载入表格
            });
        },
        save: function () {

            var dataTable = $(".layui-table-body.layui-table-main tr");// 行数据
            // console.log(dataTable)
            var tableBak = [];
            var dataBak = table.cache['LAY-genius-table'];
            //
            for (var i = 0; i < dataBak.length; i++) {
                if (dataBak[i].actionType == 'add') {
                    dataBak[i].goodscode = goodscode;
                    dataBak[i].system = objid;
                }

                var din = $(dataTable[i]).find('td:eq(6) input:eq(0)').attr('value');
                var tui = $(dataTable[i]).find('td:eq(6) input:eq(1)').attr('value');
                //复选框
                if (din == '1' && tui == '1') {
                    dataBak[i].attribute = '1,1';
                } else if (din == '0' && tui == '0') {
                    dataBak[i].attribute = '0,0';
                } else if (din == '1' && tui == '0') {
                    dataBak[i].attribute = '1,0';
                } else if (din == '0' && tui == '1') {
                    dataBak[i].attribute = '0,1';
                }

                // console.log($(dataTable[i]).find('td:eq(6) input:eq(0)').attr('value'))
                // console.log($(dataTable[i]).find('td:eq(6) input:eq(0)').attr('value'))

                tableBak.push(dataBak[i]);
            }
            // console.log(tableBak)
            layui.admin.req({
                url: layui.setter.host + '/goods_system_supplier/editall'
                , type: 'post'
                , dataType: 'json'
                , contentType: "application/json; charset=utf-8"
                , data: JSON.stringify(tableBak)
                , done: function (res) {
//							console.log(res);
                    //请求成功后修改状态为编辑
                    if (res.status == setter.response.statusCode.status_Success) {
//								console.log(table);
                        //带查询条件
//							 	var grouphaveCol = [];
//							 	grouphaveCol.push({"colName":"goodscode","colValue":goodscode});
//							 	grouphaveCol.push({"colName":"flag","colValue":0});
//						 		grouphaveCol.push({"colName":"id","colValue":objid});
//								table.reload("LAY-genius-table",{url: setter.host + '/goods_system_supplier/getSelectBody',where:{'haveCol':grouphaveCol}});
                    }
                    layer.msg(res.msg);
                    // table.reload('LAY-genius-table');
                    loadTable(objid)
                }
            });
        }


    }


    $('.layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });


});
//---------------------------------------------------------------------------
//roleTable = table.render({
//elem: '#LAY-role-list1'
//,url:'/unite_platform/goods_class/getclasslabel'
//,cols: [[
//{type:'checkbox'}
//,{field:'id', width:80, title: 'ID', sort: true}
//,{field:'name', width:80, title: '用户名'}
//]]
//,page: true
//});



